package com.github.controller;

import com.github.service.AdminUserServer;
import com.github.util.JwtUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AdminUserServer adminUserServer;

    // 登录接口
    @PostMapping("/login")
    public ApiResponse login(@RequestBody LoginRequest request, HttpServletRequest httpServletRequest) {
        String username = request.getUsername();
        String password = request.getPassword();

        if (adminUserServer.login(username, password)) {
            String token = JwtUtil.generateToken(username);
            httpServletRequest.getSession().setAttribute("username", username);
            httpServletRequest.getSession().setAttribute("token", token);
            return new ApiResponse("success", "登录成功！");
        } else {
            return new ApiResponse("error", "用户名或密码错误！");
        }
    }

    // 统一返回格式
    @Data
    public static class ApiResponse {
        private String status;
        private String message;
        private Object data;

        public ApiResponse(String status, String message, Object data) {
            this.status = status;
            this.message = message;
            this.data = data;
        }

        public ApiResponse(String status, String message) {
            this.status = status;
            this.message = message;
        }
    }

    // 登录请求体
    @Data
    public static class LoginRequest {
        private String username;
        private String password;
    }
}